package org.itli.jnsocket.Service.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.DTO.ProductDTO;
import org.itli.jnsocket.Mapper.OutboundMapper;
import org.itli.jnsocket.Pojo.Customer;
import org.itli.jnsocket.Pojo.Goods;
import org.itli.jnsocket.Pojo.Outbound;
import org.itli.jnsocket.Service.OutboundService;
import org.itli.jnsocket.Util.OrderIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.List;

@Slf4j
@Service
public class OutboundServiceImpl implements OutboundService {

    OutboundMapper mapper;

    @Autowired
    public void setMapper(OutboundMapper mapper) {
        this.mapper = mapper;
    }

    OrderIdGenerator uuid = new OrderIdGenerator();

    @Override
    @Transactional(rollbackFor = Exception.class) // 确保所有异常都会触发回滚
    public String OutBounds(Outbound outbound, String username) {
        String result = "1";
        String Order_sn = uuid.generateOrderId();
        try {
            Customer customers = mapper.SelectCustomer(outbound.getCustomer_id());
            if (customers == null) {
                // 如果没有找到客户，抛出异常
                throw new RuntimeException("Customer not found");

            }

            int i = mapper.Insert_sale_order(customers, outbound.getOrder_amount(),
                    outbound.getOrder_date(), "S", username,
                    username, Order_sn, outbound.getRemark(),
                    outbound.getWarehouse_id());
            if (i != 1) { // 假设i为1表示插入成功
                //return "插入失败";
                throw new RuntimeException("Insert sale order failed");
            }

            log.info("插入销售表完成");
            int order_id = mapper.SelectOrderID(Order_sn);
            if (order_id == 0) { // 假设order_id为0表示未找到
                throw new RuntimeException("Order ID not found");
            }

            for (ProductDTO good : outbound.getGoods()) {
                String s = mapper.SelectGoodsSN(good.getGoods_id());
                if (s == null) {
                    //return "商品表错误";
                    throw new RuntimeException("Goods SN not found for goods ID: " + good.getGoods_id());
                }
                good.setGoods_sn(s);
                String s1 = mapper.SelectGoodsSec(good.getGoods_id());
                if (s1 == null) {
                    //return "商品表错误";
                    throw new RuntimeException("Goods spec not found for goods ID: " + good.getGoods_id());
                }
                good.setGoods_spec(s1);
                log.info("数据已经全部集齐：" + good.toString());

                mapper.Insert_sale_order_goods(order_id, Order_sn, good, username, username);
                log.info("插入商品表事件完成");

                Goods goods = null;
                int stock;

                try{
                    goods = mapper.SelectGoods_Stock(good.getGoods_id(), outbound.getWarehouse_id());
                    if(goods == null){
                        throw new RuntimeException("Stock not found for goods ID");
                    }else {
                        stock = goods.getGoods_stock();
                        if (stock == 0) { // 假设stock为0表示库存不足
                            //return "库存不足";
                            //当库存不足时，删除当前表内的关于该商品的记录
                            try{
                                mapper.Delete_Goods_Stock(good.getGoods_id());
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                            throw new RuntimeException("Stock不足 for goods ID: " + good.getGoods_id());
                        }
                        stock -= good.getGoods_count();
                        mapper.UpdateGoods_Stock(good.getGoods_id(), outbound.getWarehouse_id(), stock);
                        log.info("完成插入");
                        result = "1";
                    }
                } catch (Exception e) {
                    log.info("错误信息：该仓库未找到该商品");
                    //return "仓库错误";
                    throw new RuntimeException(e);
                }
            }
        } catch (Exception e) {
            log.error("Error occurred during OutBounds operation", e);
            throw e; // 重新抛出异常，确保事务回滚
        }

        if(result.equals("1")){
            return "1";
        }
        else {
            return "error";
        }
    }
}
